import os

import aiomysql
from tornado import web, ioloop


class MainHandler(web.RequestHandler):

    def initialize(self, db):
        self.db = db

    async def get(self, *args, **kwargs):
        pool = await aiomysql.create_pool(**self.db)
        async with pool.acquire() as conn:
            async with conn.cursor(cursor=aiomysql.cursors.DictCursor) as cur:
                await cur.execute("select * from messages")
                result = await cur.fetchone()

        if result is None:
            result = {}
        return self.render('message.html', message=result)

    async def post(self, *args, **kwargs):
        id = self.get_body_argument("id")
        print(id)
        result = {
            "nickname": self.get_body_argument("name"),
            "email": self.get_body_argument("email"),
            "address": self.get_body_argument("address"),
            "message": self.get_body_argument("message")
        }

        pool = await aiomysql.create_pool(**self.db)
        async with pool.acquire() as conn:
            async with conn.cursor(cursor=aiomysql.cursors.DictCursor) as cur:

                if id == "None":
                    sql = "INSERT INTO `messages`(`nickname`, `email`, `address`, `message`) values('{nickname}','{email}','{address}','{message}')".format(**result)
                else:
                    sql = "UPDATE `messages` SET `nickname`='{nickname}',`email`='{email}',`address`='{address}',`message`='{message}' where id={id}".format(
                        id=id, **result)
                print(sql)
                await cur.execute(sql)
                await conn.commit()
        self.redirect(self.reverse_url('index'))


if __name__ == '__main__':
    base_dir = os.path.dirname(__file__)
    setting = {
        "static_path": os.path.join(base_dir, 'static'),
        'static_url_prefix': "/static/",  # 设置静态文件路径前缀
        'template_path': os.path.join(base_dir, 'templates'),
        'gzip': True,
        'db': {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "",
            "db": "messages",
            "charset": "utf8"
        }
    }

    urls = [
        web.URLSpec("/", MainHandler, {"db": setting['db']}, name='index'),
    ]

    app = web.Application(urls, debug=False, **setting)
    app.listen(8000)

    ioloop.IOLoop.current().start()
